// router.js
import { getToken } from '@/utils/auth'
import {RouterMount,createRouter} from 'uni-simple-router';
let num = 0;
const router = createRouter({
	platform: process.env.VUE_APP_PLATFORM,
	routerErrorEach(error, router) {
		// uni-simple-router把uniapp默认的退出应用的效果给拦截了，因此需要手动单独处理一下
		if (error.uniActualData.from == 'backbutton') {
			num++;
			if (num > 1) {
				plus.runtime.quit();
			} else {
				// plus.nativeUI.toast('再按一次退出应用');
				plus.nativeUI.toast('Press again to exit the application');
			}
			setTimeout(() => {
				num = 0;
			}, 1500);
		}
		// 路由跳转解锁，否则首页点击物理返回键后，路由锁定，跳转失败...
		if (error.type === 3) {
			router.$lockStatus = false;
		}
	},
	// 通配符，非定义页面，跳转404
	routes: [...ROUTES,
		{
			path: '*',
			redirect: (to) => {
				return {
					name: '404'
				}
			}
		},
	]
});

//全局路由前置守卫
router.beforeEach((to, from, next) => {
	let token = getToken();
	//判断该路由是否需要登录权限
	if(to.meta.requireAuth){
		if(token){
			next();
		}
		else{ 
			next('/pages/register/login');
		}
	}
	else{
		next();
	}
});

export {
	router,
	RouterMount
}